package com.cherrish.demo.nio;

import com.cherrish.demo.SocketConst;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Date;

/**
 * @author cherrish
 * @time 2019-04-26 16:14
 * @name NioClient
 * @desc:
 */
public class NioClient {
    public static void main(String[] args) {
        NioClient nioClient = new NioClient();
        nioClient.start();
    }
    public void start(){
        try {
            init();
            sendAndRecv();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private SocketChannel socketChannel = null;

    private void init() throws IOException {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(SocketConst.ADDRESS, SocketConst.PORT);
        socketChannel = SocketChannel.open(inetSocketAddress);
    }

    private void sendAndRecv() throws IOException {
        String message = "I'm client, It's " + new Date().toString();
        ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes(SocketConst.CHARSET));
        socketChannel.write(byteBuffer);
        byteBuffer.clear();
        socketChannel.read(byteBuffer);
        System.out.println("recv from server: " + new String(byteBuffer.array(), SocketConst.CHARSET));
        socketChannel.close();
    }
}
